# $Id: utils.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__ = "$Revision: 7557b5d4d82b $"
__author__ = "$Author: pgurumur $"

import urllib2
import random
import StringIO

from django.conf import settings
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.template import loader, RequestContext, Context
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.http import HttpResponseServerError

from aptools.lib import exception, log, stdlib

FORBIDDEN = 1
NOTFOUND = 2
INTERROR = 3
NOTALLOWED = 4

handle404 = lambda request: aptools_error(request, NOTFOUND)
handle500 = lambda request: aptools_error(request, INTERROR)
media_url = lambda request: { 'media_url' : settings.MEDIA_URL }

def syslog_enabled(Name):
   retval = None
   if hasattr(settings, 'SYSLOG'):
      if ('HOST' in settings.SYSLOG) and ('PORT' in settings.SYSLOG):
         retval = log.SysLog(
               Name, settings.SYSLOG['HOST'], settings.SYSLOG['PORT'])

   return retval

def loghandle(Name):
   retval = syslog_enabled(Name)
   if not retval:
      if hasattr(settings, 'DEBUG') and settings.DEBUG:
         retval = log.StreamLog(Name)
      else:
         retval = log.NullLog(Name)

   return retval

def get_context(request = None, **Keywords):
   log = loghandle(get_context.__name__)
   ctx = {}
   ctx.update(csrf(request))
   for keys in Keywords.keys():
      if Keywords[keys]:
         ctx[keys] = Keywords[keys]

   return RequestContext(request, ctx)

def template_string():
   return loader.render_to_string

def aptools_error(request, code, **kwargs):
   retval = None
   if code == FORBIDDEN:
      kwargs['title'] = 'forbidden'
      retval = HttpResponseForbidden(loader.get_template(
         settings.TEMPLATES['FORBIDDEN']).render(
            RequestContext(request, get_context(request, **kwargs))))
   elif code == NOTFOUND:
      kwargs['title'] = 'page not found'
      retval = HttpResponseNotFound(loader.get_template(
         settings.TEMPLATES['NOTFOUND']).render(
            RequestContext(request, get_context(request, **kwargs))))
   elif code == INTERROR:
      kwargs['title'] = 'internal error'
      retval = HttpResponseServerError(loader.get_template(
         settings.TEMPLATES['INTERROR']).render(
            RequestContext(request, get_context(request, **kwargs))))
   elif code == NOTALLOWED:
      kwargs['title'] = 'bad method'
      retval = HttpResponseNotAllowed(loader.get_template(
         settings.TEMPLATES['NOTALLOWED']).render(
            RequestContext(request, get_context(request, **kwargs))))

   return retval

def get_prefixlen():
   retval = []
   for ix in xrange(4, 129, 4):
      retval.append(ix)

   return retval

def get_rfc():
   rfcval = random.randint(1, settings.MAX_RFC)
   rfcurl = "%s/rfc%d.txt" %(settings.RFC_URL, rfcval)
   retval = StringIO.StringIO()
   url = None
   try:
      url = urllib2.urlopen(rfcurl)
   except urllib2.URLError, message:
      raise ValueError, message
   except urllib2.HTTPError, message:
      raise ValueError, message
   else:
      retval.write(url.read())
      retval.seek(0)

   return retval
